package com.dingwei.superiordiary.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bobomee.android.mentions.edit.MentionEditText;
import com.bumptech.glide.Glide;
import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.adapter.adapter.PicAdapter;
import com.dingwei.superiordiary.app.MyApplication;
import com.dingwei.superiordiary.bean.MyCarePersonalBean;
import com.dingwei.superiordiary.mvp.presenter.ReleaseCommunityPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.utils.SoftInputUtils;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.DisplayUtil;
import com.lihao.baselibrary.utils.KeyboardUtils;
import com.lihao.baselibrary.weight.MyGridView;
import com.lihao.baselibrary.weight.MyRadioGroup;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created time 2018/1/24.
 * Creator 南柯一梦丶 on
 * Personal signature 余生还长 何必慌张
 * Page description : 发布社区内容
 *
 * @author Li Hao
 */

public class ReleaseCommunityActivity extends BaseActivity implements Contract.ReleaseCommunityView {

    ReleaseCommunityPresenter releaseCommunityPresenter = new ReleaseCommunityPresenter(this);
    @Bind(R.id.img_back)
    ImageView imgBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.rb_complex)
    RadioButton rbComplex;
    @Bind(R.id.rb_personal)
    RadioButton rbPersonal;
    @Bind(R.id.m_radio_group)
    MyRadioGroup mRadioGroup;
    @Bind(R.id.et_content)
    MentionEditText etContent;
    @Bind(R.id.gridview)
    MyGridView gridview;
    @Bind(R.id.video_bg)
    ImageView videoBg;
    @Bind(R.id.img_play)
    ImageView imgPlay;
    @Bind(R.id.delete)
    ImageView delete;
    @Bind(R.id.video_layout)
    RelativeLayout videoLayout;
    @Bind(R.id.rl_root)
    View rlRoot;
    @Bind(R.id.data_layout)
    LinearLayout dataLayout;
    @Bind(R.id.img_pic)
    ImageView imgPic;
    @Bind(R.id.img_video)
    ImageView imgVideo;
    @Bind(R.id.img_hide)
    ImageView imgHide;
    @Bind(R.id.bottom_layout)
    ScrollView bottomLayout;


    private List<LocalMedia> photoList = new ArrayList<>();
    private LocalMedia video_path;
    private PicAdapter picAdapter;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_release;
    }

    @Override
    protected void initData() {

    }


    /**
     * 刷新图片集合展示
     */
    public void refreshPic() {
        if (picAdapter == null) {
            picAdapter = new PicAdapter(this, photoList,
                    DisplayUtil.getDisplayWidthPixels(this), new MyBack());
            gridview.setAdapter(picAdapter);
        } else {
            picAdapter.setList(photoList);
            picAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void initView() {
        tvTitle.setText("新建帖子");
        tvRight.setText("发布");
    }

    @Override
    protected void initListener() {
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 1 && !TextUtils.isEmpty(s)) {
                    char mentionChar = s.toString().charAt(start);
                    int selectionStart = etContent.getSelectionStart();
                    if (mentionChar == '@') {
                        intent = new Intent(BaseActivity.context, aitePersonalActivity.class);
                        intent.putExtra("userid", BaseActivity.value.getUserId());
                        startActivityForResult(intent, 1001);
                        etContent.getText().delete(selectionStart - 1, selectionStart);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    @OnClick({R.id.img_back, R.id.tv_right, R.id.img_pic, R.id.img_video,
            R.id.img_hide, R.id.rl_root, R.id.img_play
            , R.id.delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_right:
                String type;
                if (rbComplex.isChecked()) {
                    type = "0";
                } else {
                    type = "1";
                }
                CharSequence convertMetionString = etContent.getFormatCharSequence();
                releaseCommunityPresenter.save(photoList, video_path, type, convertMetionString.toString());
                break;
            case R.id.img_pic:
                CheckImage();
                break;
            case R.id.img_video:
                checkVideo();
                break;
            case R.id.img_hide:
                KeyboardUtils.hideSoftInput(this);
                break;
            case R.id.rl_root:
                SoftInputUtils.showSoftInputFromWindow(this, etContent);
                KeyboardUtils.showSoftInput(this);
                break;
            case R.id.img_play:
                PictureSelector.create(ReleaseCommunityActivity.this).externalPictureVideo(video_path.getPath());
                break;
            case R.id.delete:
                video_path = null;
                videoBg.setImageResource(0);
                videoLayout.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    public void checkVideo() {
        if (photoList != null && photoList.size() > 0) {
            showToast("只能选择一种文件类型");
            return;
        }
        PictureSelector.create(ReleaseCommunityActivity.this)
                .openGallery(PictureMimeType.ofVideo())
                .theme(R.style.picture_white_style)
                .maxSelectNum(1)
                .imageSpanCount(3)
                .previewVideo(true)
                .enablePreviewAudio(false)
                .isCamera(true)
                .imageFormat(PictureMimeType.PNG)
                .videoMaxSecond(60)
                .videoMinSecond(10)
                .forResult(189);
    }

    public void CheckImage() {
        if (video_path != null) {
            showToast("只能选择一种文件类型");
            return;
        }

        List<LocalMedia> localMediaList = new ArrayList<>();
        localMediaList.addAll(photoList);
        for (int i = 0; i < photoList.size(); i++) {
            if (TextUtils.isEmpty(photoList.get(i).getCompressPath())) {
                localMediaList.remove(i);
                break;
            }
        }
        PictureSelector.create(ReleaseCommunityActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_white_style)
                .imageSpanCount(3)
                .maxSelectNum(9)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .isZoomAnim(true)
                .selectionMedia(localMediaList)
                .enableCrop(false)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .previewEggs(true) // 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                .minimumCompressSize(100) // 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                photoList.clear();
                for (LocalMedia localMedia : selectList) {
                    if (!TextUtils.isEmpty(localMedia.getCompressPath())) {
                        photoList.add(localMedia);
                    }

                }
                photoList.add(new LocalMedia());
                if (photoList.size() == 10) {
                    photoList.remove(photoList.size() - 1);
                }
                refreshPic();
                gridview.setVisibility(View.VISIBLE);
                videoLayout.setVisibility(View.GONE);
            }
        }
        if (requestCode == 189) {
            if (data != null) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                video_path = selectList.get(0);
                gridview.setVisibility(View.GONE);
                videoLayout.setVisibility(View.VISIBLE);
                Glide.with(context)
                        .load(video_path.getPath())
                        .apply(MyApplication.options)
                        .into(videoBg);
            }
        }
        if (requestCode == 1001) {
            MyCarePersonalBean.DataBean.ListBean user = (MyCarePersonalBean.DataBean.ListBean) data.getSerializableExtra("user");
            etContent.insert(user);
        }
    }

    @Override
    public void saveSuccess() {
        intent = new Intent();
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    public void onFail() {
        tvRight.setEnabled(true);
    }

    /**
     * 点击图片上删除按钮的回调函数
     */
    class MyBack implements PicAdapter.Back {

        @Override
        public void back() {
            CheckImage();
        }

        @Override
        public void delete(int index) {
            // TODO Auto-generated method stub
            if (photoList.size() == 9) {
                photoList.remove(index);
                boolean isAdd = true;
                for (int i = 0; i < photoList.size(); i++) {
                    LocalMedia photoItem = photoList.get(i);
                    if (TextUtils.isEmpty(photoItem.getCompressPath())) {
                        isAdd = false;
                        break;
                    }
                }
                if (isAdd) {
                    photoList.add(new LocalMedia());
                }
            } else if (photoList.size() == 2) {
                photoList.clear();
            } else {
                photoList.remove(index);
            }
            refreshPic();
        }

    }
}
